import React, { useEffect, useState } from "react";
import { Button, Col, Form, Input, InputNumber, Row, Modal, Select } from "antd";
import { useTranslation } from 'react-i18next';
import { SYSCODE, CONFIG_ITEM_KEYS, RES_MODE } from '../../../utils/constant';
import { apiSysDictSelect, apiSysTemplateList, apiSysTemplateInitiate } from '../../../services/common';
import { transformArray } from '../../../utils/commonUtil';
import { useNavigate } from 'react-router-dom';

const RequestTplModal = ({
  setNewModalVisible,
  newModalVisible,
  newTplInitiateCallbackFn,
  moduleConfig,
}) => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [initialData, setInitialData] = useState({
    moduleName: moduleConfig?.moduleNames?.length === 1 ? moduleConfig?.moduleNames?.[0] : '',
  });
  const [buList, setBuList] = useState([]);
  const [moduleList, setModuleList] = useState([]);
  const [templateList, setTemplateList] = useState([]);
  const { BU, MODULE } = CONFIG_ITEM_KEYS;

  const apiGetOptionsListAsync = async () => {
    const params = {
      sysCode: SYSCODE,
      dictCodes: [BU]
    };
    const { data } = await apiSysDictSelect(params);
    setBuList(transformArray(data?.data?.[BU]));
    setModuleList(transformArray(moduleConfig?.moduleNames));
  };
  // initiate
  const initiateClickHandel = () => {
    form.validateFields().then((res) => {
      moduleConfig?.detailsUrl && navigate(moduleConfig?.detailsUrl, {
        state: {
          tplId: form.getFieldsValue()?.template,
          tBu: form.getFieldsValue()?.buType,
          tMd: form.getFieldsValue()?.moduleName,
          tTm: templateList?.filter(item => item.value === form.getFieldsValue()?.template)?.[0]?.label,
          editMode: RES_MODE.NEW
        }
      });
    }, () => {
      return false;
    });
  };
  const onChangeHandle = (val, name) => {
    if (form.getFieldsValue()?.buType && form.getFieldsValue()?.moduleName) {
      const params = {
        buType: form.getFieldsValue()?.buType,
        moduleName: form.getFieldsValue()?.moduleName,
      };
      apiSysTemplateList(params).then((res) => {
        if (res?.data?.code === 200) {
          setTemplateList(res?.data?.data?.items);
        }
      });
    };
  };
  useEffect(() => {
    apiGetOptionsListAsync();
  }, []);
  return (
    <Modal
      title={t('common.new')}
      width={540}
      onCancel={() => setNewModalVisible(false)}
      open={newModalVisible}
      footer={[
        <Button type="primary" key='initiate' onClick={() => { initiateClickHandel() }}>{t('common.initiate')}</Button>
      ]}>
      <Form form={form} initialValues={initialData}>
        <Form.Item name="buType"
          rules={[
            {
              required: true,
              message: t('common.selectRequired'),
            }]}
          label={t('common.bu')} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
          <Select placeholder={t('common.pleaseSelect')} allowClear options={buList} onChange={(val) => onChangeHandle(val, 'bu')} />
        </Form.Item>
        <Form.Item name="moduleName"
          rules={[
            {
              required: true,
              message: t('common.selectRequired'),
            }]}
          label={t('common.module')} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
          <Select placeholder={t('common.pleaseSelect')} allowClear options={moduleList} onChange={(val) => onChangeHandle(val, 'module')} />
        </Form.Item>
        <Form.Item name="template"
          rules={[
            {
              required: true,
              message: t('common.selectRequired'),
            }]}
          label={t('common.template')} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
          <Select placeholder={t('common.pleaseSelect')} allowClear options={templateList} />
        </Form.Item>
      </Form>
    </Modal>
  )
};

export default RequestTplModal;